<template>
  <div class="list" ref="wrapper">
    <div>
      <div class="area">
        <div class="title border-topbottom">当前城市</div>
        <div class="button-list">
          <div class="button-wrapper">
            <div class="button active">{{city}}</div>
          </div>
        </div>
      </div>
      <div class="area">
        <div class="title border-topbottom">热门城市</div>
        <div class="button-list">
          <div
            v-for="item of hotCities"
            :key="item.id"
            class="button-wrapper"
            @click="handleClickCityButton(item.name)"
          >
            <div class="button">{{item.name}}</div>
          </div>
        </div>
      </div>
      <div
        v-for="(item, key) of cities"
        class="area"
        :key="key"
        :ref="key"
      >
        <div class="title border-topbottom">{{key}}</div>
        <div class="item-list">
          <div
            v-for="innerItem of item"
            :key="innerItem.id"
            class="item border-bottom"
            @click="handleClickCityButton(innerItem.name)"
          >
            {{innerItem.name}}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapState, mapMutations} from 'vuex'
export default {
  name: 'CityList',
  props: {
    cities: Object,
    hotCities: Array,
    letter: String
  },
  computed: {
    ...mapState(['city'])
  },
  // 监听变量的变化
  watch: {
    letter () {
      if (this.letter) {
        // scrollToElement这是better-scroll内部方法
        const element = this.$refs[this.letter][0]
        this.scroll.scrollToElement(element)
      }
    }
  },
  methods: {
    handleClickCityButton (name) {
      this.changeCity(name)
      this.$router.push('/')
    },
    ...mapMutations({
      changeCity: 'CHANGE_CITY'
    })
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper)
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/variable.styl'
  .border-topbottom
    &:before
      border-color #ddd
    &:after
      border-color #ddd
  .border-bottom
    &:before
      border-color #ddd
  .list
    position absolute
    top 1.58rem
    left 0
    right 0
    bottom 0
    overflow hidden
    .area
      background-color #fff
      .title
        height: .8rem
        line-height .8rem
        text-indent .2rem
        background-color #F5F5F5
      .button-list
        padding .1rem .6rem .1rem .1rem
        overflow hidden
        color #666
        .button-wrapper
          float left
          width 33.33%
          .button
            margin .1rem
            padding .1rem 0
            border .02rem solid #ccc
            border-radius .06rem
            text-align center
            &.active
              color $themeColor
              border-color $themeColor
      .item-list
        color #666
        .item
          height .76rem
          line-height .76rem
          padding-left .2rem
</style>
